package com.atguigu.spzx.cloud.order.controller;

import com.atguigu.spzx.cloud.order.entity.Order;
import com.atguigu.spzx.cloud.order.entity.PatternProperties;
import com.atguigu.spzx.cloud.order.entity.User;
import com.atguigu.spzx.cloud.order.feign.UserFeignClient;
import com.atguigu.spzx.cloud.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@Slf4j
@RestController
@RefreshScope//刷新配置
@RequestMapping(value = "/api/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired // 需要注入LoadBalancerClient
    private LoadBalancerClient loadBalancerClient;

    @Value("${pattern.dateformat}")
    private String pattern ;

    @Autowired
    private PatternProperties patternProperties;

    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping(value = "/findOrderByOrderId/{orderId}")
    public Order findOrderByOrderId(@PathVariable("orderId") Long orderId) {
        ServiceInstance instance = loadBalancerClient.choose("spzx-cloud-user");
        int port = instance.getPort();
        Order order = orderService.findOrderByOrderId(orderId);
        Long userId = order.getUserId();
        // 使用Feign客户端调用用户服务
        User user = userFeignClient.findUserByUserId(order.getUserId());
        user.setAddress(user.getAddress() + "-" + port);
        order.setUser(user);
        log.info("UserController...findUserByUserId方法执行了... , dateformat: {} " ,  patternProperties.getDateformat());
        log.info("UserController...findUserByUserId方法执行了... , dateformat: {} " ,  pattern);//需要刷新配置后，会重新加载配置
        log.info("订单信息查询完成，用户地址: {}", user.getAddress());
        return order;

       /* // 获取负载均衡后的实际服务实例
        ServiceInstance instance = loadBalancerClient.choose("spzx-cloud-user");
        int port = instance.getPort();

        User user = restTemplate.getForObject("http://spzx-cloud-user/api/user/findUserByUserId/" + order.getUserId(), User.class);
        user.setAddress(user.getAddress() + "-" + port);
        order.setUser(user);
        log.info("UserController...findUserByUserId方法执行了... , dateformat: {} " ,  patternProperties.getDateformat());
        log.info("UserController...findUserByUserId方法执行了... , dateformat: {} " ,  pattern);//需要刷新配置后，会重新加载配置
        return order;*/
    }

}